package apptoko.com.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu;
import main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu.OnItemSelectedListener;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
import apptoko.com.ConfirmBuyActivity;
import apptoko.com.ItemBrokerActivity;
import apptoko.com.LoginActivity;
import apptoko.com.SettingsActivity;
import apptoko.com.VideoActivity;
import apptoko.com.adapter.ContentItemAdapter;
import apptoko.com.adapter.ErrorHandler;
import apptoko.com.adapter.OnPopupMenuClickListener;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.db.DatabaseHelper;
import apptoko.com.download.DownloadManager;
import apptoko.com.download.DownloadService;
import apptoko.com.download.DownloadManager.Request;
import apptoko.com.event.Event;
import apptoko.com.event.Event.BuyFailEvent;
import apptoko.com.event.Event.BuySuccessEvent;
import apptoko.com.event.Event.GetDownloadLinkFailEvent;
import apptoko.com.event.Event.GetDownloadLinkSuccess;
import apptoko.com.event.Event.GetVersionListSuccessEvent;
import apptoko.com.event.Event.OutOfGiftBox;
import apptoko.com.event.Event.RequestFailEvent;
import apptoko.com.event.Event.TopContentSuccessEvent;
import apptoko.com.event.Event.TopEndOfContentEvent;
import apptoko.com.event.Event.TopNoContentEvent;
import apptoko.com.event.Event.UserInfoSuccessEvent;
import apptoko.com.model.BannerItem;
import apptoko.com.model.ContentItemInfo;
import apptoko.com.model.DownloadLaterItem;
import apptoko.com.model.DownloadLink;
import apptoko.com.network.InstallBackgroundTask;
import apptoko.com.network.ProgressDialogManager;
import apptoko.com.util.Constants;
import apptoko.com.util.StorageUtils;
import apptoko.com.util.Utils;
import apptoko.com.view.AlertDialogManager;
import apptoko.com.view.LoadMoreListView;
import apptoko.com.view.LoadMoreListView.OnLoadMoreListener;

import com.androidquery.AQuery;
import com.appota.asdk.commons.AccessTokenUtil;
import com.appota.asdk.topup.TopupAPI;
import apptoko.com.R;
import com.devspark.appmsg.AppMsg;
import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;

public class CategoryListFragment extends BaseFragment implements OnItemClickListener, OnLoadMoreListener, OnPopupMenuClickListener {
	
	private String topType;
	private String currentStore;
	private final String KEY_CONTENT = "Fragment:List";
	private int START_NEW = 0;
	private int START_DOWNLOAD = 0;
	private boolean inited = false;
	private BackgroundTasks bgTask;
	private AQuery aq;
	private EventBus eventBus;
	private String accessToken;
	private LoadMoreListView listView;
	private ContentItemAdapter adapter;
	private List<ContentItemInfo> listContent;
	private int catId;
	private String catName;
	private String store;
	private ContentItemInfo contentItem;
	private DownloadManager downloadManager;
	private ProgressDialog pDialog;
	private boolean isWatchMovie = false;
	private String versionName = "";
	private int greenTym = -1;
	private int purpleTym = -1;
	private int versionId = 0;
	private String countryCode;
	private boolean enaG=false;
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString(KEY_CONTENT, topType);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		if (savedInstanceState != null) {
            topType = savedInstanceState.getString(KEY_CONTENT);
        }
	}
	
	private void getUserInfo(){
		String accessToken = Utils.getStaticAccessToken(getActivity());
		if(accessToken!="3de71f9e84a325bbfb86466c15b40b1e"){
			bgTask.getUserInfo(accessToken);
		}
	}
	
	public void onEventMainThread(UserInfoSuccessEvent event){
		greenTym = event.getUser().getGreenTym();
		purpleTym = event.getUser().getPurpleTym();
		getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).edit().putString(Constants.USERNAME_LOGGEDIN, event.getUser().getUserName()).commit();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		eventBus.register(this);
	}

	@Override
	public void onPause() {
		super.onPause();
		eventBus.unregister(this);
	}
	
	public void init() {
		if (inited) {
			return;
		}
		inited = true;
		loadData(0);
//		if(countryCode.equalsIgnoreCase("vn")){
//			loadTextAd();
//		}
	}
	
	private void loadTextAd() {
		String bannerStore;
		if(currentStore.equalsIgnoreCase("books")){
			bannerStore = "ebook_android";
		} else if(currentStore.equalsIgnoreCase("comics")){
			bannerStore = "comic_android";
		} else if(currentStore.equalsIgnoreCase("movies")){
			bannerStore = "film_android";
		} else {
			bannerStore = "android";
		}
		bgTask.getTextBanners(accessToken, bannerStore, topType);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mParent = inflater.inflate(R.layout.layout_listing, null);
		aq = new AQuery(mParent);
		listView = (LoadMoreListView) mParent.findViewById(R.id.list_content);
		adapter = new ContentItemAdapter(getActivity(), R.layout.short_content_item, listContent);
		adapter.setStore(currentStore);
		adapter.setOnPopupMenuClickListener(this);
		aq.id(listView).adapter(adapter).itemClicked(this);
		listView.setOnLoadMoreListener(this);
		aq.id(R.id.btn_retry).gone();
		aq.id(R.id.progress).visible();
		return mParent;
	}
	
	private void loadData(int start){
		if(topType.equalsIgnoreCase(getResources().getString(R.string.top_new))){
			getTopNew(start);
		} else if(topType.equalsIgnoreCase(getResources().getString(R.string.top_download))){
			getTopDownload(start);
		} else if(topType.equalsIgnoreCase(getResources().getString(R.string.top_paid))){
			getTopPaid(start);
		} else if(topType.equalsIgnoreCase(getResources().getString(R.string.hot_app))){
			getHot(start);
		}
	}
	
	private void getHot(int start){
		int storeId = 2;
		if(currentStore.equals("android") || currentStore.equals("game") || currentStore.equals("home")){
			storeId = 2;
		} else if(currentStore.equals("film")){
			storeId = 6;
		} else if(currentStore.equals("ebook")){
			storeId = 4;
		} else if(currentStore.equals("comic")){
			storeId = 5;
		}
		bgTask.getHotItemByCateId(getResources().getString(R.string.hot_app), accessToken, storeId, catId, start);
	}
	
	private void getTopPaid(int start) {
		// TODO Auto-generated method stub
		int storeId = 2;
		if(currentStore.equals("android") || currentStore.equals("game") || currentStore.equals("home")){
			storeId = 2;
		} else if(currentStore.equals("film")){
			storeId = 6;
		} else if(currentStore.equals("ebook")){
			storeId = 4;
		} else if(currentStore.equals("comic")){
			storeId = 5;
		}
		bgTask.getTopContent(getResources().getString(R.string.top_paid), catId, accessToken, storeId, start);
	}
	
	private void getTopDownload(int start) {
		// TODO Auto-generated method stub
		int storeId = 2;
		if(currentStore.equals("games") || currentStore.equals("apps") || currentStore.equals("home")){
			storeId = 2;
		} else if(currentStore.equals("movies")){
			storeId = 6;
		} else if(currentStore.equals("books")){
			storeId = 4;
		} else if(currentStore.equals("comics")){
			storeId = 5;
		}
		
		bgTask.getTopContent(getResources().getString(R.string.top_download), catId, accessToken, storeId, start);
	}

	private void getTopNew(int start){
		int storeId = 2;
		if(currentStore.equals("apps") || currentStore.equals("games") || currentStore.equals("home")){
			storeId = 2;
		} else if(currentStore.equals("movies")){
			storeId = 6;
		} else if(currentStore.equals("books")){
			storeId = 4;
		} else if(currentStore.equals("comics")){
			storeId = 5;
		}
		
		bgTask.getTopContent(getResources().getString(R.string.top_new), catId, accessToken, storeId, start);
	}

	@Override
	protected void initVariables() {
		// TODO Auto-generated method stub
		EasyTracker.getInstance().setContext(mContext);
		countryCode = Utils.getStaticCountryCode(mContext);
		SharedPreferences shared= getActivity().getSharedPreferences("system_pre", Activity.MODE_PRIVATE);
		enaG=shared.getBoolean(Constants.ENABLE_GUEST, false);
		accessToken = Utils.getStaticAccessToken(getActivity());
		topType = getArguments().getString(Constants.TOP);
		currentStore = getArguments().getString(Constants.STORE_KEY);
		bgTask = new BackgroundTasks(getActivity());
		eventBus = EventBus.getDefault();
		listContent = new ArrayList<ContentItemInfo>();
		catId = getArguments().getInt(Constants.CATEGORY_ID);
		catName = getArguments().getString(Constants.CATEGORY_NAME);
		downloadManager = new DownloadManager(mContext.getContentResolver(), mContext.getPackageName());
	    downloadManager.setAccessAllDownloads(false);
		startDownloadService();
	}
	
	private void startDownloadService() {
		Intent intent = new Intent();
		intent.setClass(getActivity(), DownloadService.class);
		getActivity().startService(intent);
	}
	
	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		//EasyTracker.getInstance().activityStop(getActivity());
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		EasyTracker.getTracker().sendView(currentStore + "/Category/" + catName);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) {
		// TODO Auto-generated method stub
		ContentItemInfo item = (ContentItemInfo) parent.getItemAtPosition(position);
		EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.VIEW_EVENT_ACTION, item.getTitle(), Long.valueOf(1));
		if(item.getApplicationId().startsWith("market")||item.getApplicationId().startsWith("http")){
			try {
			    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(item.getApplicationId())));
			} catch (android.content.ActivityNotFoundException anfe) {
			}
		}else{
			Intent intent = new Intent(getActivity(), ItemBrokerActivity.class);
			intent.putExtra(Constants.PREVIOUS_SCREEN, currentStore + "/Category/" + catName);
			intent.putExtra(Constants.SLUG, item.getApplicationId());
			intent.putExtra(Constants.KEY_REFERER, "direct");
			intent.putExtra(Constants.STORE_KEY, getArguments().getString(Constants.STORE_KEY));
			startActivity(intent);
		}
		
	}

	public void onEventMainThread(TopContentSuccessEvent event){
		if(event.getTopType().equalsIgnoreCase(topType)){
			aq.id(listView).visible();
			aq.id(R.id.btn_retry).gone();
			aq.id(R.id.progress).gone();
			aq.id(R.id.text_no_content).gone();
			for (ContentItemInfo item : event.getItemList()) {
				listContent.add(item);
			}
			adapter.notifyDataSetChanged();
			listView.onLoadMoreComplete();
		}
	}
	
	public void onEventMainThread(RequestFailEvent event){
		aq.id(listView).gone();
		aq.id(R.id.btn_retry).visible().clicked(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				aq.id(listView).gone();
				listView.setOnLoadMoreListener(CategoryListFragment.this);
				aq.id(R.id.btn_retry).gone();
				aq.id(R.id.progress).visible();
				aq.id(R.id.text_no_content).gone();
				loadData(0);
//				if(countryCode.equalsIgnoreCase("vn")){
//					loadTextAd();
//				}
			}
		});
		aq.id(R.id.progress).gone();
		ErrorHandler.getInstance().setContext(getActivity()).handleError(event.getErrorCode());
		listView.setOnLoadMoreListener(null);
	}
	
	public void onEventMainThread(TopNoContentEvent e){
		if(e.getType().equalsIgnoreCase(topType)){
			aq.id(listView).gone();
			aq.id(R.id.btn_retry).gone();
			aq.id(R.id.progress).gone();
			aq.id(R.id.text_no_content).visible();
		}
	}
	
	public void onEventMainThread(TopEndOfContentEvent e){
		if(e.getType().equalsIgnoreCase(topType)){
			listView.onLoadMoreComplete();
			listView.setOnLoadMoreListener(null);
		}
	}
	
	private class OnBannerClickListener implements OnClickListener {
		
		private BannerItem banner;
		
		public OnBannerClickListener(BannerItem banner){
			this.banner = banner;
		}

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.VIEW_EVENT_ACTION, "ClickListBanner " + banner.getName(), Long.valueOf(1));
			if(banner.getSlug().startsWith("market")||banner.getSlug().startsWith("http")){
				try {
				    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(banner.getSlug())));
				} catch (android.content.ActivityNotFoundException anfe) {
				}
			}else{
				Intent intent = new Intent(getActivity(), ItemBrokerActivity.class);
				intent.putExtra(Constants.PREVIOUS_SCREEN, currentStore + "/" + topType);
				intent.putExtra(Constants.SLUG, banner.getSlug());
				intent.putExtra(Constants.KEY_REFERER, "ads");
				intent.putExtra(Constants.STORE_KEY, getArguments().getString(Constants.STORE_KEY));
				startActivity(intent);
			}
			
		}
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		if (topType.equalsIgnoreCase(getResources().getString(R.string.top_new).toUpperCase(Locale.US))) {
			if(listContent.size()==START_NEW+20){
				START_NEW = START_NEW + 20;
				loadData(START_NEW);
			}else{
				listView.onLoadMoreComplete();
				listView.setOnLoadMoreListener(null);
			}
			
		} else if (topType.equalsIgnoreCase(getResources().getString(R.string.top_download).toUpperCase(Locale.US))) {
			if(listContent.size()==START_DOWNLOAD+20){
				START_DOWNLOAD = START_DOWNLOAD + 20;
				loadData(START_DOWNLOAD);
			}else{
				listView.onLoadMoreComplete();
				listView.setOnLoadMoreListener(null);
			}
			
		}
	}

	@Override
	protected void initActions() {
		// TODO Auto-generated method stub
		if(topType.equalsIgnoreCase(getResources().getString(R.string.top_new))){
			getTopNew(0);
//			if(countryCode.equalsIgnoreCase("vn")){
//				loadTextAd();
//			}
//			getUserInfo();
		}
	}
	
	private boolean checkLogin(){
		return Utils.getStaticIsLogin(getActivity());
	}
	
	private void download(final ContentItemInfo item, final int isBought){
		AlertDialogManager am = new AlertDialogManager(mContext);
		am.showWebViewDialog(aq, item.getInstallAttachApplication(), mContext, item.getPermission(), R.string.app_permissions, item.getAttachApplicationAvatar(), item.getAttachApplicationTitle(), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				pDialog = ProgressDialogManager.showProgressDialog(mContext, R.string.loading);
				if(item.getPrice() != 0){
					validAndBuy(item.getPrice(), "green", item, 0, isBought);
				} else if(item.getPrice2() != 0){
					validAndBuy(item.getPrice2(), "purple", item, 0, isBought);
				} else {
					validAndBuy(0, "free", item, 0, isBought);
				}
				dialog.dismiss();
			}
		});
	}

	@Override
	public void onInstallClicked(String store, final ContentItemInfo item) {
		// TODO Auto-generated method stub
		EasyTracker.getTracker().sendEvent(Constants.DOWNLOAD_EVENT_CATEGORY, Constants.LIST_DOWNLOAD_ACTION, item.getTitle() + " in " + item.getApplicationType() + " store", Long.valueOf(1));
		this.store = store;
		this.contentItem = item;
		isWatchMovie = false;
		if(enaG){
			//allow e
			if(true){//checkLogin()
				checkGift();
			} else {
				AlertDialogManager am = new AlertDialogManager(mContext);
				am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						switch (which) {
						case DialogInterface.BUTTON_POSITIVE:
							Intent intent = new Intent(getActivity(), LoginActivity.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							startActivity(intent);
							break;
						case DialogInterface.BUTTON_NEGATIVE:
							dialog.dismiss();
							break;
						}
					}
				});
			}
		}else{
			if(!countryCode.equalsIgnoreCase("vn")&&!countryCode.equalsIgnoreCase("id")&&!countryCode.equalsIgnoreCase("my")){
				if(item.getRootLink()!=null&&item.getRootLink()!=""){
					Intent gp = new Intent(Intent.ACTION_VIEW);
					gp.setData(Uri.parse(item.getRootLink()));
					startActivity(gp);
				}else{
					AppMsg.makeText(getActivity(), "This item has no link currently", AppMsg.STYLE_ALERT, null).show();
				}
				
			} else {
				if(true){//checkLogin()
					checkGift();
				} else {
					AlertDialogManager am = new AlertDialogManager(mContext);
					am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
								Intent intent = new Intent(getActivity(), LoginActivity.class);
								intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								startActivity(intent);
								break;
							case DialogInterface.BUTTON_NEGATIVE:
								dialog.dismiss();
								break;
							}
						}
					});
				}
			}
		}
		
	}

	@Override
	public void onAddToWishListClicked(String store, ContentItemInfo item) {
		// TODO Auto-generated method stub
		this.store = store;
		String addType = null;
		if(store.equalsIgnoreCase("home") || store.equalsIgnoreCase("apps") || store.equalsIgnoreCase("games")){
			addType = Constants.ANDROID_STORE;
		} else if(store.equalsIgnoreCase("books")){
			addType = "ebook";
		} else if(store.equalsIgnoreCase("comics")){
			addType = "comic";
		} else {
			addType = "film";
		}
		DatabaseHelper db = new DatabaseHelper(mContext);
		DownloadLaterItem dlItem = new DownloadLaterItem(item.getAvatar(), item.getTitle(), item.getAuthor(), item.getApplicationId());
		dlItem.setPrice1(item.getPrice());
		dlItem.setPrice2(item.getPrice2());
		dlItem.setPackageName(item.getPackageName());
		dlItem.setType(addType);
		boolean added = db.addDownloadLater(dlItem);
		if(added){
			Toast.makeText(mContext, String.format(getResources().getString(R.string.saved), item.getTitle()), Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(mContext, String.format(getResources().getString(R.string.item_exist), item.getTitle()), Toast.LENGTH_SHORT).show();
		}
	}
	
	public void onEventMainThread(BuySuccessEvent event){
		if(event.getTopType().equalsIgnoreCase(topType)){
			String accessToken = Utils.getStaticAccessToken(getActivity());
			bgTask.getDownloadLink(topType, accessToken, event.getSlug(), versionId, Utils.getStaticIsRooted(getActivity()), "direct");
		}
	}
	
	public void onEventMainThread(BuyFailEvent event){
		if(event.getTopType().equalsIgnoreCase(topType)){
			if(pDialog != null){
				pDialog.dismiss();
			}
			AppMsg.makeText(getActivity(), event.getMessage(), AppMsg.STYLE_ALERT, null).show();
		}
	}
	
	private void checkGift(){
		if(contentItem.getGiftbox() == 1){
			bgTask.checkRemainGift(accessToken, contentItem.getApplicationId());
		} else {
			download(contentItem, 0);
		}
	}
	
	
	public void onEventMainThread(OutOfGiftBox e){
		download(contentItem, 1);
	}
	
	public void onEventMainThread(GetDownloadLinkSuccess event){
		if(event.getTopType().equalsIgnoreCase(topType)){
			if(pDialog != null){
				pDialog.dismiss();
			}
			if(contentItem.getInstallAttachApplication() == 1){
				accessToken = Utils.getStaticAccessToken(getActivity());
				bgTask.buyAttachedContent(accessToken, contentItem.getAttachApplicationSlug(), 0);
			}
			if(isWatchMovie){
				Intent watch = new Intent(getActivity(), VideoActivity.class);
				watch.putExtra(Constants.MOVIE_URL, event.getDl().getDownload());
				watch.putExtra(Constants.MOVIE_TITLE, contentItem.getTitle());
				watch.putExtra(Constants.MOVIE_EPISODE, versionName);
				watch.putExtra(Constants.KEY_PRICE_1, contentItem.getPrice());
				watch.putExtra(Constants.KEY_PRICE_2, contentItem.getPrice2());
				watch.putExtra(Constants.KEY_VERSION, versionId);
				watch.putExtra(Constants.KEY_SLUG, contentItem.getApplicationId());
				watch.putExtra(Constants.IS_MOVIE_PURCHASED, contentItem.getBought());
				startActivity(watch);
			} else {
				DownloadLink download = event.getDl();
				List<String> extraUrls = download.getExtraDownloads();
				if(extraUrls.size() > 0&&extraUrls.get(0).length()>3){
					for(String extraUrl : extraUrls){
						Uri srcUri = Uri.parse(extraUrl.replace(" ", "%20"));
						DownloadManager.Request request = new Request(srcUri);
						if(extraUrl.endsWith("obb")){
							String obbDir = StorageUtils.OBB_ROOT + contentItem.getPackageName() + "/";
							File obb = new File(obbDir);
							if(!obb.exists()){
								obb.mkdirs();
							}
							request.setDestinationUri(Uri.fromFile(new File(obbDir + Utils.getFileName(extraUrl))));	
						} else {
							request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(extraUrl))));
						}
						request.setTitle(String.format(getResources().getString(R.string.additional_file), contentItem.getTitle()));
						request.setDescription(contentItem.getAvatar());
						request.setMimeType(StorageUtils.APPS_ROOT.toLowerCase(Locale.US));
						downloadManager.enqueue(request);
					}
				}
				if(event.getSlug().equalsIgnoreCase(contentItem.getApplicationId())){
					String url = download.getDownload();
					Uri srcUri = Uri.parse(url.replace(" ", "%20"));
					DownloadManager.Request request = new Request(srcUri);
					request.setTitle(contentItem.getTitle());
					request.setDescription(contentItem.getAvatar());
					setDownloadData(request, url, store);
					downloadManager.enqueue(request);
				} else {
					String url = download.getDownload();
					Uri srcUri = Uri.parse(url.replace(" ", "%20"));
					DownloadManager.Request request = new Request(srcUri);
					request.setTitle(event.getSlug());
					request.setDescription("");
					setDownloadData(request, url, "apps");
					downloadManager.enqueue(request);
				}
			}
		}
	}
	
	public void onEventMainThread(GetDownloadLinkFailEvent e){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		AppMsg.makeText(getActivity(), e.getMessage(), AppMsg.STYLE_ALERT, null).show();
	}
	
	private void setDownloadData(Request request, String url, String store){
		request.setWhere(topType);
		if(store.equalsIgnoreCase("apps") || store.equalsIgnoreCase("games") || store.equalsIgnoreCase("home")){
			request.setMimeType(StorageUtils.APPS_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(url))));
		} else if(store.equalsIgnoreCase("books")){
			request.setMimeType(StorageUtils.EBOOK_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.EBOOK_ROOT + Utils.getFileName(url))));
		} else if(store.equalsIgnoreCase("comics")){
			request.setMimeType(StorageUtils.COMIC_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.COMIC_ROOT + Utils.getFileName(url))));
		} else if(store.equalsIgnoreCase("movies")){
			request.setMimeType(StorageUtils.MOVIES_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.MOVIES_ROOT + Utils.getFileName(url))));
		} else {
			request.setMimeType(StorageUtils.DATA_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.DATA_ROOT + Utils.getFileName(url))));
		}
	}

	@Override
	public void onDownloadClicked(String store, ContentItemInfo item) {
		// TODO Auto-generated method stub
		EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.LIST_DOWNLOAD_ACTION, item.getTitle() + " in " + item.getApplicationType() + " store", Long.valueOf(1));
		this.store = store;
		isWatchMovie = false;
		if(checkLogin()){
			contentItem = item;
			pDialog = ProgressDialogManager.showProgressDialog(mContext, R.string.loading);
			accessToken = Utils.getStaticAccessToken(getActivity());
			bgTask.getVersionList(accessToken, item.getApplicationId(), topType);
		} else {
			AlertDialogManager am = new AlertDialogManager(mContext);
			am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						Intent intent = new Intent(getActivity(), LoginActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(intent);
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						dialog.dismiss();
						break;
					}
				}
			});
		}
	}

	@Override
	public void onLaunchClicked(String packageName) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onWatchClicked(ContentItemInfo item) {
		// TODO Auto-generated method stub
		store = "movies";
		if(checkLogin()){
			isWatchMovie = true;
			contentItem = item;
			pDialog = ProgressDialogManager.showProgressDialog(mContext, R.string.loading);
			accessToken = Utils.getStaticAccessToken(getActivity());
			bgTask.getVersionList(accessToken, item.getApplicationId(), topType);
		} else {
			AlertDialogManager am = new AlertDialogManager(mContext);
			am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						Intent intent = new Intent(getActivity(), LoginActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(intent);
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						dialog.dismiss();
						break;
					}
				}
			});
		}
	}
	
	public void onEventMainThread(GetVersionListSuccessEvent event){
		if(pDialog != null){
			pDialog.dismiss();
		}
		if(event.getTopType().equalsIgnoreCase(topType)){
			if(event.getVersionList().size() == 1){
				if(store.equalsIgnoreCase("books") || store.equalsIgnoreCase("comics")){
					pDialog = ProgressDialogManager.showProgressDialog(mContext, R.string.loading);
					if(contentItem.getPrice() != 0){
						validAndBuy(contentItem.getPrice(), "green", contentItem, 0, contentItem.getBought());
					} else if(contentItem.getPrice2() != 0){
						validAndBuy(contentItem.getPrice2(), "purple", contentItem, 0, contentItem.getBought());
					} else {
						validAndBuy(0, "free", contentItem, 0, contentItem.getBought());
					}
				} else {
					versionId = event.getVersionList().get(0).getId();
					pDialog = ProgressDialogManager.showProgressDialog(getActivity(), R.string.loading);
					accessToken = Utils.getStaticAccessToken(getActivity());
					bgTask.watchMovie(topType, accessToken, contentItem.getApplicationId(), versionId, Utils.getStaticIsRooted(getActivity()), "direct");
				}
				versionId = event.getVersionList().get(0).getId();
				pDialog = ProgressDialogManager.showProgressDialog(getActivity(), R.string.loading);
				accessToken = Utils.getStaticAccessToken(getActivity());
				bgTask.watchMovie(topType, accessToken, contentItem.getApplicationId(), versionId, Utils.getStaticIsRooted(getActivity()), "direct");
			} else {
				PopupMenu popupMenu = new PopupMenu(mContext);
				popupMenu.setHeaderTitle(getResources().getString(R.string.choose_episode));
				String versionName;
				int versionId;
				int price1;
				int price2;
				for (int i = event.getVersionList().size()-1; i >= 0; i--) {
					versionId = event.getVersionList().get(i).getId();
					versionName = event.getVersionList().get(i).getName();
					price1 = event.getVersionList().get(i).getPrice1();
					price2 = event.getVersionList().get(i).getPrice2();
					popupMenu.add(versionId, versionName, "", price1, price2, true).setIcon(getResources().getDrawable(R.drawable.ic_arrow_down));
				}  
				popupMenu.setOnItemSelectedListener(new OnItemSelectedListener() {
					@Override
					public void onItemSelected(final main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
						// TODO Auto-generated method stub
						CategoryListFragment.this.versionId = menuItem.getItemId();
						CategoryListFragment.this.versionName = menuItem.getTitle();
						if(store.equalsIgnoreCase("books") || store.equalsIgnoreCase("comics")){
							bgTask.checkVersionBought(topType, accessToken, null, menuItem);
						} else {
							pDialog = ProgressDialogManager.showProgressDialog(getActivity(), R.string.loading);
							accessToken = Utils.getStaticAccessToken(getActivity());
							bgTask.watchMovie(topType, accessToken, contentItem.getApplicationId(), menuItem.getItemId(), Utils.getStaticIsRooted(getActivity()), "direct");
						}
					}
				});
				popupMenu.show();
			}
		}
	}
	
	private void validAndBuy(int price, String tymType, ContentItemInfo item, int versionId, int isBought){
		if(isBought == 1){
			if(pDialog == null){
				pDialog = ProgressDialogManager.showProgressDialog(getActivity(), R.string.loading);
			}
			bgTask.buyContent("", Utils.getStaticAccessToken(getActivity()), item.getApplicationId(), versionId);
		} else {
			if(tymType.equals("green")){
				if(greenTym < price && greenTym != -1){
					AlertDialogManager am = new AlertDialogManager(mContext);
					am.showButtonsDialog(R.string.lack_of_tym, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
//								Intent intent = new Intent(getActivity(), PaymentActivity.class);
//								Bundle bundle = new Bundle();
//								bundle.putInt(AccountActivity.KEY_GREEN_TYM, greenTym);
//								bundle.putInt(AccountActivity.KEY_PURPLE_TYM, purpleTym);
//								intent.putExtras(bundle);
//								startActivity(intent);
								List<String> scopes = new ArrayList<String>();
								scopes.add("user.info");
								scopes.add("user.email");
								TopupAPI.getInstance().setContext(getActivity()).topupTYM(scopes, "");
								break;
							case DialogInterface.BUTTON_NEGATIVE:
								dialog.dismiss();
								break;
							}
						}
					});
				} else if(greenTym == -1){
					AlertDialogManager am = new AlertDialogManager(mContext);
					am.showPositiveDialog(R.string.cannot_buy_thistime, android.R.string.ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
				} else {
					Intent intent = new Intent(getActivity(), ConfirmBuyActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString(Constants.KEY_IMAGE, item.getAvatar());
					bundle.putString(Constants.KEY_NAME, item.getTitle());
					bundle.putString(Constants.KEY_AUTHOR, item.getAuthor());
					bundle.putInt(Constants.KEY_PRICE_1, item.getPrice());
					bundle.putInt(Constants.KEY_PRICE_2, item.getPrice2());
					bundle.putLong(Constants.KEY_VERSION, Long.valueOf(versionId));
					bundle.putString(Constants.KEY_EP, versionName);
					bundle.putString(Constants.KEY_SLUG, item.getApplicationId());
					intent.putExtras(bundle);
					startActivityForResult(intent, 0);
				}
			} else if(tymType.equals("purple")){
				if(purpleTym < price && purpleTym != -1){
					AlertDialogManager am = new AlertDialogManager(mContext);
					am.showButtonsDialog(R.string.lack_of_tym, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
//								Intent intent = new Intent(getActivity(), PaymentActivity.class);
//								Bundle bundle = new Bundle();
//								bundle.putInt(AccountActivity.KEY_GREEN_TYM, greenTym);
//								bundle.putInt(AccountActivity.KEY_PURPLE_TYM, purpleTym);
//								intent.putExtras(bundle);
//								startActivity(intent);
								List<String> scopes = new ArrayList<String>();
								scopes.add("user.info");
								scopes.add("user.email");
								TopupAPI.getInstance().setContext(getActivity()).topupTYM(scopes, "");
								break;
							case DialogInterface.BUTTON_NEGATIVE:
								dialog.dismiss();
								break;
							}
						}
					});
				} else if(purpleTym == -1){
					AlertDialogManager am = new AlertDialogManager(mContext);
					am.showPositiveDialog(R.string.cannot_buy_thistime, android.R.string.ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
				} else {
					Intent intent = new Intent(getActivity(), ConfirmBuyActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString(Constants.KEY_IMAGE, item.getAvatar());
					bundle.putString(Constants.KEY_NAME, item.getTitle());
					bundle.putString(Constants.KEY_AUTHOR, item.getAuthor());
					bundle.putInt(Constants.KEY_PRICE_1, item.getPrice());
					bundle.putInt(Constants.KEY_PRICE_2, item.getPrice2());
					bundle.putLong(Constants.KEY_VERSION, Long.valueOf(versionId));
					bundle.putString(Constants.KEY_EP, versionName);
					bundle.putString(Constants.KEY_SLUG, item.getApplicationId());
					intent.putExtras(bundle);
					startActivityForResult(intent, 0);
				}
			} else if(tymType.equals("free")){
				bgTask.getDownloadLink(topType, AccessTokenUtil.getInstance().init(getActivity()).getSavedAccessToken(), item.getApplicationId(), versionId, Utils.getStaticIsRooted(getActivity()), "direct");
//				bgTask.buyContent(topType, Utils.getStaticAccessToken(getActivity()), item.getApplicationId(), versionId);
			}
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, intent);
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		if(requestCode == 0 && resultCode == Activity.RESULT_OK){
			AppMsg.makeText(getActivity(), R.string.buy_success, AppMsg.STYLE_INFO, null).show();
			String accessToken = Utils.getStaticAccessToken(getActivity());
			bgTask.getDownloadLink(topType, accessToken, intent.getExtras().getString(Constants.SLUG), intent.getExtras().getLong(Constants.KEY_VERSION), Utils.getStaticIsRooted(getActivity()), "direct");
		}
	}
	
	public void onEventMainThread(final Event.DownloadFailEvent e){
		if(e.getReferer().equalsIgnoreCase(topType)){
			if(e.getMessage() != null){
				if(e.getMessage().contains("exist")){
					AlertDialogManager am = new AlertDialogManager(getActivity());
					am.showFileDowloadDialog(store, R.string.install_already_exist_file, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
								if(store.equalsIgnoreCase("apps") || store.equalsIgnoreCase("games") || store.equalsIgnoreCase("home")){
									boolean autoInstall = getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).getBoolean(SettingsActivity.KEY_AUTO_INSTALL, false);
						    		if(!autoInstall){
						    			Utils.installAPK(getActivity(), StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()));
						    		} else {
						    			InstallBackgroundTask task = new InstallBackgroundTask(getActivity());
						    			task.execute(StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()), contentItem.getTitle());
						    		}
								} else if(store.equalsIgnoreCase("books")){
									openEbook(StorageUtils.EBOOK_ROOT + Utils.getFileName(e.getPath()));
								} else if(store.equalsIgnoreCase("comics")){
									openComic(StorageUtils.COMIC_ROOT + Utils.getFileName(e.getPath()));
								} else {
									Intent watch = new Intent(getActivity(), VideoActivity.class);
									watch.putExtra(Constants.MOVIE_URL, StorageUtils.MOVIES_ROOT + Utils.getFileName(e.getPath()));
									watch.putExtra(Constants.MOVIE_TITLE, Utils.getFileName(e.getPath()));
									watch.putExtra(Constants.MOVIE_EPISODE, "");
									watch.putExtra(Constants.KEY_PRICE_1, 0);
									watch.putExtra(Constants.KEY_PRICE_2, 0);
									watch.putExtra(Constants.KEY_VERSION, 0);
									watch.putExtra(Constants.KEY_SLUG, "");
									watch.putExtra(Constants.IS_MOVIE_PURCHASED, true);
									startActivity(watch);
								}
								break;
							case DialogInterface.BUTTON_NEGATIVE:
								if(store.equalsIgnoreCase("apps") || store.equalsIgnoreCase("games") || store.equalsIgnoreCase("home")){
									Utils.deleteFile(StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()));
								} else if(store.equalsIgnoreCase("books")){
									Utils.deleteFile(StorageUtils.EBOOK_ROOT + Utils.getFileName(e.getPath()));
								} else if(store.equalsIgnoreCase("comics")){
									Utils.deleteFile(StorageUtils.COMIC_ROOT + Utils.getFileName(e.getPath()));
								} else {
									Utils.deleteFile(StorageUtils.MOVIES_ROOT + Utils.getFileName(e.getPath()));
								}
								break;
							case DialogInterface.BUTTON_NEUTRAL:
								dialog.dismiss();
								break;
							}
						}
					});
				} else {
					AppMsg.makeText(getActivity(), e.getMessage(), AppMsg.STYLE_ALERT, null).show();
				}
			}
			downloadManager.remove(e.getId());
		}
	}
	
	public void openEbook(String path){
		if(Utils.checkCoolReader(mContext, path)){
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.parse(path), "application/epub+zip");
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		} else {
			AlertDialogManager am = new AlertDialogManager(mContext);
			am.showDialog(R.string.no_ebook_reader, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					AlertDialogManager am = new AlertDialogManager(getActivity());
					String items[] = {"Cool Reader"};
					am.showDialogWithItems(R.string.choose_book_reader_app, items, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface v, int pos) {
							// TODO Auto-generated method stub
							accessToken = Utils.getStaticAccessToken(getActivity());
							bgTask.buyContent(topType, accessToken, "cooldreader", 0);
						}
					});
				}
			});
		}
	}
	
	private void openComic(String path){
		if(Utils.checkDroidComicViewer(getActivity(), path)){
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.parse(path), "application/x-acv");
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		} else {
			AlertDialogManager am = new AlertDialogManager(getActivity());
			am.showDialog(R.string.no_comic_reader, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					AlertDialogManager am = new AlertDialogManager(getActivity());
					String items[] = {"Droid Comic Viewer"};
					am.showDialogWithItems(R.string.choose_book_reader_app, items, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface v, int pos) {
							// TODO Auto-generated method stub
							accessToken = Utils.getStaticAccessToken(getActivity());
							bgTask.buyContent(topType, accessToken, Utils.ACV_SLUG, 0);
						}
					});
				}
			});
		}
	}
}
